/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.swapper.json.spi.supports;

import com.swapper.json.*;
import com.swapper.reflect.TypeHelper;
import com.swapper.reflect.creator.InstanceCreator;

import java.lang.reflect.Type;
import java.util.Map;
import java.util.Objects;

/**
 * The map wrapper factory.
 *
 * @see java.util.Map<>
 */
public enum MapWrapperFactory implements JsonWrapperFactory {
  INSTANCE;

  @SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  public <T> JsonWrapper<T> create(JsonContext context, Type type) {
    Class<?> rawType = context.getRawType(type);
    Type[] types = TypeHelper.getMapKeyAndValueTypes(type, rawType);
    if (types != null) {
      InstanceCreator<T> creator = context.getInstanceCreator(type);
      JsonWrapper<?> keyWrapper = context.findWrapper(types[0]);
      JsonWrapper<?> valueWrapper = context.findWrapper(types[1]);
      return new MapWrapper(creator, keyWrapper, valueWrapper);
    }
    return null;
  }

  private static final class MapWrapper<K, V, T extends Map<K, V>> implements JsonWrapper<T> {
    private final InstanceCreator<T> _creator;
    private final JsonWrapper<K> _keyWrapper;
    private final JsonWrapper<V> _valueWrapper;

    public MapWrapper(InstanceCreator<T> creator, JsonWrapper<K> keyWrapper, JsonWrapper<V> valueWrapper) {
      _creator = Objects.requireNonNull(creator);
      _keyWrapper = Objects.requireNonNull(keyWrapper);
      _valueWrapper = Objects.requireNonNull(valueWrapper);
    }

    @Override
    public JsonValue wrap(T value) {
      if (value == null) {
        return JsonValue.NULL;
      }
      JsonObject jsonObject = new JsonObject();
      for (Map.Entry<K, V> entry : value.entrySet()) {
        jsonObject.put(_keyWrapper.wrap(entry.getKey()).toString(),
          _valueWrapper.wrap(entry.getValue()));
      }
      return jsonObject;
    }

    @Override
    public T unwrap(JsonValue value) {
      if (JsonValue.NULL.equals(value)) {
        return null;
      }
      JsonObject jsonObject = value.toJsonObject();
      T map = _creator.create();
      for (Map.Entry<String, JsonValue> entry : jsonObject.members()) {
        JsonString string = JsonString.valueOf(entry.getKey());
        map.put(_keyWrapper.unwrap(string), _valueWrapper.unwrap(entry.getValue()));
      }
      return map;
    }
  }
}
